<template>
  <div ref="VProgressBar" class="v-progress-bar" :style="outerStyles" v-show="show">
    <div class="v-progress-bar__inner" :class="innerClasses" :style="styles"></div>
  </div>
</template>
<script>
  export default {
    name: 'VProgeressBar',
    props: {
      color: {
        type: String,
        default: 'primary',
      },
      errorColor: {
        type: String,
        default: 'error',
      },
      height: {
        type: Number,
        default: 2,
      },
    },
    data() {
      return {
        percent: 0,
        status: 'success',
        show: false,
        speed: 50,
      };
    },
    computed: {
      innerClasses() {
        return {
          'v-progress-bar__inner--default': this.color === 'primary' && this.status === 'success',
          'v-progress-bar__inner--error': this.errorColor === 'error' && this.status === 'error',
        };
      },
      outerStyles() {
        return {
          height: `${this.height}px`,
        };
      },
      styles() {
        const style = {
          width: `${this.percent}%`,
          height: `${this.height}px`,
        };

        if (this.color !== 'primary' && this.status === 'success') {
          style.backgroundColor = this.color;
        }

        if (this.errorColor !== 'error' && this.status === 'error') {
          style.backgroundColor = this.errorColor;
        }
        return style;
      },
    },
    methods: {
      config() {},
      start() {
        clearTimeout(this.$timer);
        this.percent = 0;
        this.show = true;
        this.status = 'success';
        this.$emit('start');
        this.move();
      },
      done() {
        this.percent = 100;
        setTimeout(() => {
          this.show = false;
        }, 350);
        this.$emit('done');
        clearTimeout(this.$timer);
      },
      error() {
        this.status = 'error';
        this.done();
      },
      increase() {
        const between = (v, min, max) => {
          if (max <= min) {
            return min;
          }
          return Math.min(max, Math.max(min, v));
        };
        const inc = (p, a) => {
          let amount = a;
          if (typeof amount !== 'number') {
            if (p < 25) {
              amount = Math.random() * 6;
            } else if (p < 65) {
              amount = Math.random() * 5;
            } else if (p < 85) {
              amount = Math.random() * 4;
            } else if (p < 99) {
              amount = 0.5;
            } else {
              amount = 0;
            }
          }
          return between(p + amount, 0, 100);
        };

        this.percent = inc(this.percent);
      },
      move() {
        this.$timer = setTimeout(() => {
          this.increase();
          this.move();
        }, this.speed);
      },
    },
    beforeDestroy() {
      clearTimeout(this.$timer);
    },
  };
</script>
